#!/bin/sh

### BEGIN INIT INFO
# Provides: datadog-agent-process
# Short-Description: Start and stop datadog process agent
# Description: Datadog Process Agent
# Required-Start: $remote_fs
# Required-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
### END INIT INFO

ETC_DIR="<%= etc_dir %>"
INSTALL_DIR="<%= install_dir %>"
AGENTPATH="$INSTALL_DIR/embedded/bin/process-agent"
PIDFILE="$INSTALL_DIR/run/process-agent.pid"
AGENT_ARGS="--config=$ETC_DIR/datadog.yaml --pid=$PIDFILE"
AGENT_USER="dd-agent"
NAME="datadog-agent-process"
DESC="Datadog Process Agent"

# Shell functions sourced from /etc/rc.status (sourced by /lib/lsb/init-functions):
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_failed        set local and overall rc status to failed
#      rc_failed <num>  set local and overall rc status to <num>
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status

# Shell functions sourced from /lib/lsb/init-functions:
#      start_daemon
#      killproc
#      pidofproc
#      log_success_msg
#      log_failure_msg
#      log_warning_msg
. /lib/lsb/init-functions

# Return values acc. to LSB for all commands but status:
# 0 - success
# 1 - generic or unspecified error
# 2 - invalid or excess argument(s)
# 3 - unimplemented feature (e.g. "reload")
# 4 - insufficient privilege
# 5 - program is not installed
# 6 - program is not configured
# 7 - program is not running
#
# Note that starting an already running service, stopping
# or restarting a not-running service as well as the restart
# with force-reload (in case signalling is not supported) are
# considered a success.

rc_reset

if [ ! -x $AGENTPATH ]; then
  echo "$AGENTPATH not found. Exiting $NAME"
  exit 1
fi

if [ -r "/etc/default/${NAME}" ]; then
  . "/etc/default/${NAME}"
fi

do_start() {
  # If the Agent is already running, return success
  checkproc $AGENTPATH
  if [ "$?" -eq "0" ]; then
    return 0
  fi
  startproc -f -q -u $AGENT_USER -p $PIDFILE $AGENTPATH $AGENT_ARGS
}

start_and_wait() {
  # Start the Agent
  do_start
  case "$?" in
    0)
      # Wait until the Agent is running
      retries=5
      while [ $retries -gt 1 ]; do
        checkproc $AGENTPATH
        if [ "$?" -eq "0" ]; then
          # Successfully started.
          log_success_msg
          return 0
        else
          retries=$(($retries - 1))
          sleep 1
        fi
      done
      # Report an error if the Agent didn't start after 5 seconds
      log_failure_msg
      return 1
      ;;
    *)
      # Report an error if the Agent didn't manage to start
      log_failure_msg
      return 1
      ;;
  esac
}

do_stop() {
  checkproc $AGENTPATH
  # If the Agent is not running, return success
  if [ "$?" -eq "3" ]; then
    return 0
  fi

  killproc -TERM -p $PIDFILE $AGENTPATH
  RETVAL="$?"
  rm -f $PIDFILE
  return $RETVAL
}

stop_and_wait() {
  # Stop the Agent
  do_stop
  case "$?" in
    0) 
      # Successfully stopped.
      log_success_msg 
      return 0
      ;;
    *) 
      # Report an error if the Agent didn't manage to stop
      log_failure_msg 
      return 1
      ;;
  esac
}

case "$1" in
  start)
    if [ "$DATADOG_ENABLED" = "no" ]; then
      echo "Disabled via /etc/default/$NAME. Exiting."
      exit 0
    fi

    echo -n "Starting $DESC"
    start_and_wait
    
    # Remember error code for rc_exit
    rc_status
    ;;
  stop)
    echo -n "Shutting down $DESC"
    stop_and_wait
    
    # Remember error code for rc_exit
    rc_status
    ;;
  restart|reload)
    ## Stop the service and regardless of whether it was
    ## running or not, start it again.
    $0 stop
    $0 start

    # Remember error code for rc_exit
    rc_status
    ;;
  status)
    echo -n "Checking for $DESC:"

    # Status codes are slightly different for the checkproc command:
    # 0 - service running
    # 1 - service dead, but /var/run/  pid  file exists
    # 2 - service dead, but /var/lock/ lock file exists
    # 3 - service not running
    checkproc $AGENTPATH

    # Remember error code for rc_exit and print status
    rc_status -v
    ;;
  *)
    N=/etc/init.d/$NAME
    echo "Usage: $N {start|stop|restart|reload|status}"
    exit 1
    ;;
esac

rc_exit

